package jrobutt;

public class CollisionMaster
{
    // gotten from: http://www.gmlscripts.com/script/lines_intersect
    public static Vector2 lines_intersection_result (
        float line1_x1, float line1_y1, float line1_x2, float line1_y2,
        float line2_x1, float line2_y1, float line2_x2, float line2_y2)
    {
        float ud = (line2_y2 - line2_y1) * (line1_x2 - line1_x1) - (line2_x2 - line2_x1) * (line1_y2 - line1_y1);
        if (ud == 0) return null;
        
        float ua = ((line2_x2 - line2_x1) * (line1_y1 - line2_y1) - (line2_y2 - line2_y1) * (line1_x1 - line2_x1)) / ud;
        float ub = ((line1_x2 - line1_x1) * (line1_y1 - line2_y1) - (line1_y2 - line1_y1) * (line1_x1 - line2_x1)) / ud;
        return new Vector2(ua, ub);
    }
    
    public static boolean are_overlapping (
        float line_x1, float line_y1, float line_x2, float line_y2,
        float rect_x, float rect_y, float rect_width, float rect_height)
    {
        if (line_x1 >= rect_x && line_x1 <= rect_x + rect_width &&
            line_y1 >= rect_y && line_y1 <= rect_y + rect_height)
        {
            return true;
        }
        
        if (line_x2 >= rect_x && line_x2 <= rect_x + rect_width &&
            line_y2 >= rect_y && line_y2 <= rect_y + rect_height)
        {
            return true;
        }
        
        Vector2 v;
        v = lines_intersection_result(
            line_x1, line_y1, line_x2, line_y2,
            rect_x, rect_y, rect_x + rect_width, rect_y);
        if (v != null && v.x >= 0.0f && v.x <= 1.0f && v.y >= 0.0f && v.y <= 1.0f)
        {
            return true;
        }
        
        v = lines_intersection_result(
            line_x1, line_y1, line_x2, line_y2,
            rect_x, rect_y, rect_x, rect_y + rect_height);
        if (v != null && v.x >= 0.0f && v.x <= 1.0f && v.y >= 0.0f && v.y <= 1.0f)
        {
            return true;
        }
        
        v = lines_intersection_result(
            line_x1, line_y1, line_x2, line_y2,
            rect_x, rect_y+rect_height, rect_x + rect_width, rect_y+rect_height);
        if (v != null && v.x >= 0.0f && v.x <= 1.0f && v.y >= 0.0f && v.y <= 1.0f)
        {
            return true;
        }
        
        v = lines_intersection_result(
            line_x1, line_y1, line_x2, line_y2,
            rect_x+rect_width, rect_y, rect_x+rect_width, rect_y + rect_height);
        if (v != null && v.x >= 0.0f && v.x <= 1.0f && v.y >= 0.0f && v.y <= 1.0f)
        {
            return true;
        }
        
        return false;
    }
}
